import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/I10n/translations.dart';
import 'package:sainbainu/common/services/app.dart';
import 'package:sainbainu/common/utils/loading.dart';

import 'index.dart';

class Language {
  final String title;
  final Locale locale;

  Language({required this.title, required this.locale});
}

class LanguageController extends GetxController {
  LanguageController();

  final state = LanguageState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();

    state.languageList = [
      Language(title: '简体中文', locale: const Locale('zh', 'CN')),
      Language(title: 'English', locale: const Locale('en', 'US')),
    ];
    state.selectedLocale = AppTranslations.currentLocale;
  }

  /// 检查选中
  bool checkSelected(Locale locale) {
    var currentLocale = state.selectedLocale;

    if (locale.languageCode == currentLocale?.languageCode &&
        locale.countryCode == currentLocale?.countryCode) {
      return true;
    }

    if (locale.languageCode == currentLocale?.languageCode) {
      var lang = state.languageList.firstWhereOrNull(
          (e) => e.locale.countryCode == currentLocale?.languageCode);
      if (lang == null) {
        return true;
      }
      if (lang.locale.languageCode == currentLocale?.languageCode) {
        return true;
      }
    }

    return false;
  }

  /// 选择语言
  void onSelectLanguage(Locale locale) {
    state.selectedLocale = locale;
    update();
  }

  /// 切换语言
  void onChangeLanguage() {
    if (state.selectedLocale == null) {
      return;
    }
    try {
      LoadingUtil.showLoading(text: '正在设置');
      AppTranslations.changeLocale(
        state.selectedLocale!.languageCode,
        state.selectedLocale!.countryCode,
      );
      AppService.to.setLocale(state.selectedLocale!);
      LoadingUtil.dismiss();
      Get.back();
    } catch (e) {
      LoadingUtil.showError('设置失败');
    }
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
